package com.jing;//package com.test.mqtt;

import org.eclipse.paho.client.mqttv3.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MQTTClient extends JFrame implements ActionListener {
    private JPanel contentPane;
    private Font useFont = new Font("微软雅黑", Font.BOLD, 12);
    private JFormattedTextField frmserverIP;
    private JFormattedTextField username;
    private JButton button_connect;
    private JButton button_disconnect;
    private JFormattedTextField toptic_input;
    private JFormattedTextField toptic_titile;
    private JLabel err_infoText;
    private JComboBox<String> comboBox;
    private JButton sendbutton;
    private JTextArea msgtextArea,subscriptionTextArea;
    private String brokerIP;
    private String clientId;
    private String msgContent;
    private String sub_topic, pub_topic;
    private int qos = 0;
    private MqttClient sampleClient;
    private String infoList = "";
    private JButton subbutton;

    public static void main(String[] args) throws MqttException {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MQTTClient frame = new MQTTClient();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public MQTTClient() throws MqttException {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 484, 419);
        setTitle("MQTT客户端");
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(null);
        setContentPane(contentPane);

        // 创建MQTT客户端实例（这里应该使用UI中的输入字段来动态设置）
        sampleClient = new MqttClient("tcp://127.0.0.1:1883", MqttClient.generateClientId());

        JLabel lblMqtt = new JLabel("MQTT服务器地址:");
        lblMqtt.setFont(useFont);
        lblMqtt.setBounds(30, 10, 109, 15);
        contentPane.add(lblMqtt);

        frmserverIP = new JFormattedTextField();
        frmserverIP.setText("tcp://127.0.0.1:1883");
        frmserverIP.setBounds(139, 7, 258, 21);
        contentPane.add(frmserverIP);

        JLabel lblNewLabel = new JLabel("用户名:");
        lblNewLabel.setFont(useFont);
        lblNewLabel.setBounds(40, 41, 54, 15);
        contentPane.add(lblNewLabel);

        username = new JFormattedTextField();
        username.setText("#");
        username.setBounds(139, 38, 99, 21);
        contentPane.add(username);

        button_connect = new JButton("连  接");
        button_connect.setBounds(30, 66, 93, 23);
        button_connect.setFont(useFont);
        button_connect.addActionListener(this);
        button_connect.setActionCommand("connect");
        contentPane.add(button_connect);

        button_disconnect = new JButton("断  开");
        button_disconnect.setEnabled(false);
        button_disconnect.setFont(useFont);
        button_disconnect.addActionListener(this);
        button_disconnect.setActionCommand("disconnect");
        button_disconnect.setBounds(263, 66, 93, 23);
        contentPane.add(button_disconnect);

        JLabel label = new JLabel("订阅主题:");
        label.setBounds(40, 111, 83, 15);
        label.setFont(useFont);
        contentPane.add(label);

        toptic_input = new JFormattedTextField();
        toptic_input.setText("test/#");
        toptic_input.setBounds(139, 108, 99, 21);
        contentPane.add(toptic_input);

        JSeparator separator = new JSeparator();
        separator.setBounds(30, 99, 367, 2);
        contentPane.add(separator);

        subbutton = new JButton("订  阅");
        subbutton.setFont(useFont);
        subbutton.addActionListener(this);
        subbutton.setActionCommand("sub");
        subbutton.setBounds(263, 107, 93, 23);
        contentPane.add(subbutton);

        // 创建第二个多行文本框
         subscriptionTextArea = new JTextArea();
        JScrollPane subscriptionScrollPane = new JScrollPane();
        subscriptionScrollPane.setBounds(40, 230, 316, 100); // 设置位置和大小
        subscriptionScrollPane.setViewportView(subscriptionTextArea);

// 将滚动面板添加到 contentPane
        contentPane.add(subscriptionScrollPane);

        JSeparator separator_1 = new JSeparator();
        separator_1.setBounds(30, 139, 367, 2);
        contentPane.add(separator_1);

        JLabel label_1 = new JLabel("发布消息");
        label_1.setFont(useFont);
        label_1.setBounds(40, 151, 60, 15);
        contentPane.add(label_1);

        JLabel label_2 = new JLabel("主题");
        label_2.setFont(useFont);
        label_2.setBounds(104, 151, 30, 15);
        contentPane.add(label_2);

        toptic_titile = new JFormattedTextField();
        toptic_titile.setText("test");
        toptic_titile.setBounds(139, 148, 99, 21);
        contentPane.add(toptic_titile);

        JLabel label_3 = new JLabel("服务质量");
        label_3.setFont(useFont);
        label_3.setBounds(248, 151, 54, 15);
        contentPane.add(label_3);

        comboBox = new JComboBox<String>();
        comboBox.setBounds(305, 148, 51, 21);
        comboBox.addItem("0");
        comboBox.addItem("1");
        comboBox.addItem("2");
        contentPane.add(comboBox);

        sendbutton = new JButton("发  送");
        sendbutton.setBounds(46, 338, 93, 23);
        sendbutton.addActionListener(this);
        sendbutton.setActionCommand("send");
        contentPane.add(sendbutton);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(40, 179, 316, 149);
        contentPane.add(scrollPane);

        msgtextArea = new JTextArea();
        scrollPane.setViewportView(msgtextArea);

        err_infoText = new JLabel("");
        err_infoText.setForeground(Color.RED);
        err_infoText.setBounds(134, 69, 131, 15);
        err_infoText.setFont(useFont);
        contentPane.add(err_infoText);

        JButton btnClear = new JButton("clear");
        btnClear.setBounds(209, 338, 93, 23);
        btnClear.addActionListener(this);
        btnClear.setActionCommand("clear");
        contentPane.add(btnClear);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 获取按钮的命令
        String command = e.getActionCommand();
        if (command.equals("connect")) {
            // 连接按钮
            String serverIP = frmserverIP.getText(); // 获取服务器地址
            String user = username.getText(); // 获取用户名
            MqttConnectOptions connOpts = new MqttConnectOptions(); // 创建连接选项

            connOpts.setCleanSession(true);
            connOpts.setUserName(user); // 设置用户名
//            connOpts.setPassword("".toCharArray()); // 设置密码（如有）
            // 确保这里的连接字符串只有一个 tcp:// 前缀
            connOpts.setServerURIs(new String[]{serverIP}); // 设置服务器地址

            button_connect.addActionListener(this);
            try {
                sampleClient.connect(); // 尝试连接
                button_connect.setEnabled(false); // 禁用连接按钮
                button_disconnect.setEnabled(true); // 启用断开连接按钮
                System.out.println("Connected to broker: " + serverIP);
//                123213
                subscriptionTextArea.setText("成功连接到: " + serverIP); // 显示订阅信息
            } catch (MqttException me) {
                subscriptionTextArea.setText("连接失败..."); // 显示订阅信息
                System.out.println("Reason: " + me.getReasonCode());
                System.out.println("Message: " + me.getMessage());
                System.out.println("Localized Message: " + me.getLocalizedMessage());
                System.out.println("Cause: " + me.getCause());
                me.printStackTrace();
            }

            sampleClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    System.out.println("Connection lost: " + throwable.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage msg) {
                    // 补全代码处2，连接回调处理
                    String message = new String(msg.getPayload());
                    System.out.println("Message arrived from topic: " + topic + ", message: " + message);
                    infoList += message + "\n"; // 将消息添加到列表
                    subscriptionTextArea.setText(infoList); // 显示订阅信息
                    // 可以将消息显示在某个文本区域或组件上
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 消息送达完成后的处理
                }
            });
        } else if (command.equals("sub")) {
            // 订阅按钮
            String topic = toptic_input.getText(); // 获取要订阅的主题
            try {
                String serverIP = frmserverIP.getText(); // 获取服务器地址
                sampleClient.subscribe(topic, qos); // 订阅主题，可以指定QoS
                System.out.println("Subscribed to topic: " + topic + " with QoS: " + qos);

            } catch (MqttException me) {
                me.printStackTrace();
                err_infoText.setText("订阅失败: " + me.getMessage()); // 显示错误信息
            }
        } else if (command.equals("send")) {
            // 发送按钮
            String message = msgtextArea.getText(); // 获取要发送的消息

            String topic = toptic_titile.getText(); // 获取目标主题（修正）
            qos = comboBox.getSelectedIndex(); // 获取服务质量（修正，之前未使用）

            try {
                MqttMessage mqttMessage = new MqttMessage(message.getBytes());
                mqttMessage.setQos(qos); // 设置QoS（修正）
                sampleClient.publish(topic, mqttMessage); // 发送消息
                System.out.println("Message sent to topic: " + topic + " with QoS: " + qos);
            } catch (MqttException me) {
                me.printStackTrace();
                err_infoText.setText("发送失败: " + me.getMessage()); // 显示错误信息
            }
        } else if (command.equals("clear")) {
            // 清除按钮
            msgtextArea.setText(""); // 清空消息文本区
            System.out.println("Message area cleared.");
        } else if (command.equals("disconnect")) {
            // 断开连接按钮
            try {
                sampleClient.disconnect(); // 尝试断开连接
                button_connect.setEnabled(true); // 启用连接按钮
                button_disconnect.setEnabled(false); // 禁用断开连接按钮
                System.out.println("Disconnected from broker.");
            } catch (MqttException me) {
                me.printStackTrace();
            }
        }
    }


}